/**
 * @param {number[][]} grid
 * @return {number}
 */
export var maxAreaOfIsland = function (grid) {
  let res = 0
  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid[0].length; j++) {
      if (grid[i][j] === 1) {
        res = Math.max(res, dfs(grid, i, j))
      }
    }
  }
  return res
}

function dfs(grid, rowIndex, colIndex) {
  if (rowIndex < 0 || rowIndex >= grid.length || colIndex < 0 || colIndex >= grid[0].length)
    return 0
  if (grid[rowIndex][colIndex] === 0) return 0
  grid[rowIndex][colIndex] = 0
  let res = 1
  res += dfs(grid, rowIndex - 1, colIndex)
  res += dfs(grid, rowIndex + 1, colIndex)
  res += dfs(grid, rowIndex, colIndex - 1)
  res += dfs(grid, rowIndex, colIndex + 1)
  return res
}
